﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Nasa8x.Core;
using Nasa8x.UI.Bussiness;
using Nasa8x.Web.UI.Configuration;



namespace Nasa8x.Web.UI
{
    public static class WebContext
    {

        public static HttpContext Context
        {
            get
            {

                return HttpContext.Current;
            }

        }


        public static string Encrypt(params object[] _params)
        {

            var _sb = new StringBuilder(200);

            for (int i = 0; i < _params.Length; i++)
            {

                if (i > 0)
                    _sb.Append(",");
                _sb.Append(_params[i].ToString());
            }

            // More
            _sb.AppendFormat(",{0}", SessionId);

            return Encryptor.Encrypt(_sb.ToString(), WebConfig.EncryptPassword);

        }


        public static string[] Decrypt(string _encryptString)
        {

            string _plainText = Encryptor.Decrypt(_encryptString, WebConfig.EncryptPassword);
            return _plainText.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
        }


        public static string[] Cmd
        {
            get
            {
                var _cmd = Context.Request["cmd"];

                return !string.IsNullOrWhiteSpace(_cmd) ? Decrypt(_cmd.Replace(" ", "+")) : null;

            }

        }


        public static string SessionId
        {
            get
            {
                if (Context.Session["_VISITOR"] == null)
                {
                    Context.Session["_VISITOR"] = Guid.NewGuid().ToString().Replace("-", "");
                }
                return Context.Session["_VISITOR"].ToString();


            }
        }

        public static string ClientIp
        {
            get
            {
                string _ip = Context.Request.UserHostAddress;
                if (_ip == "::1" || string.IsNullOrEmpty(_ip)) _ip = "127.0.0.1";

                return _ip;
            }
        }





        public static bool IsLogined
        {
            get
            {
                return UserInfo != null;
            }
        }




        public static string GetAbsoluteUrl(string _pageStringFormat, params object[] _params)
        {

            int _length = _params.Length + 2;
            var _args = new string[_length];
            _args[0] = WebConfig.AbsoluteUrl;// first arg set Root Path

            for (int i = 0; i < _params.Length; i++)
            {
                _args[i + 1] = _params[i].ToString();
            }
            _args[_length - 1] = WebConfig.Extension; // Last arg set extension


            return string.Format(_pageStringFormat, _args);
        }

        public static string GetAbsoluteUrl(string _pageStringFormat)
        {
            return string.Format(_pageStringFormat, WebConfig.AbsoluteUrl, WebConfig.Extension);
        }



        public static string GetDetailLink(string category, string title, int id)
        {
            if (!string.IsNullOrWhiteSpace(category))
                return GetAbsoluteUrl(SiteUrls.DETAIL_WITH_CATEGORY, ToPlainText(category), ToPlainText(title),
                                      id.ToString("X"));

            return GetAbsoluteUrl(SiteUrls.DETAIL, ToPlainText(title), id.ToString("X"));
        }


        public static string GetDetailLink(string title, int id)
        {
            return GetDetailLink(null, title, id);
        }


        public static string GetCategoryLink(string parent, string title, int id)
        {
            if (!string.IsNullOrWhiteSpace(parent))
                return GetAbsoluteUrl(SiteUrls.CATEGORY_WITH_SUB, ToPlainText(parent), ToPlainText(title), id);

            return GetAbsoluteUrl(SiteUrls.CATEGORY, ToPlainText(title), id);
        }

        public static string GetCategoryLink(string title, int id)
        {
            return GetCategoryLink(null, title, id);
        }




        public static int TotalPage(int _pageSize, int _totalRows)
        {

            int pageCount;
            if ((_totalRows % _pageSize) > 0)
                pageCount = _totalRows / _pageSize + 1;
            else
                pageCount = _totalRows / _pageSize;
            return pageCount;
        }



        public static string Replace(string input, params string[] args)
        {

            if (args.Length > 0)
            {
                return args.Aggregate(input, (_current, _t) => _current.Replace(_t, string.Empty));
            }

            return input;

        }


        public static string Price(double d)
        {
            return string.Format("{0:N0} {1}", d, WebConfig.Currency).Replace(",", ".");
        }


        #region DateTime Format


        public static string PrettyDate(DateTime _date)
        {
            // 1.
            // Get time span elapsed since the date.
            TimeSpan _s = DateTime.UtcNow.Subtract(_date);

            // 2.
            // Get total number of days elapsed.
            var _dayDiff = (int)_s.TotalDays;

            // 3.
            // Get total number of seconds elapsed.
            var _secDiff = (int)_s.TotalSeconds;

            // 4.
            // Don't allow out of range values.
            if (_dayDiff < 0 || _dayDiff >= 31)
            {
                return DateFormat(_date);
            }

            // 5.
            // Handle same-day times.
            if (_dayDiff == 0)
            {
                // A.
                // Less than one minute ago.
                if (_secDiff < 60)
                {
                    return string.Format(DateTimeFormat.JUST_NOW, _secDiff == 0 ? 1 : _secDiff); //"just now";
                }
                // B.
                // Less than 2 minutes ago.
                if (_secDiff < 120)
                {
                    return string.Format(DateTimeFormat.MINUTES_AGO, 1);// "1 minute ago";
                }
                // C.
                // Less than one hour ago.
                if (_secDiff < 3600)
                {
                    return string.Format(DateTimeFormat.MINUTES_AGO,
                        Math.Floor((double)_secDiff / 60));
                }
                // D.
                // Less than 2 hours ago.
                if (_secDiff < 7200)
                {
                    return string.Format(DateTimeFormat.HOURS_AGO, 1);
                }
                // E.
                // Less than one day ago.
                if (_secDiff < 86400)
                {
                    return string.Format(DateTimeFormat.HOURS_AGO, Math.Floor((double)_secDiff / 3600));
                }
            }
            // 6.
            // Handle previous days.
            if (_dayDiff == 1)
            {
                var _dt = _date + TimeZoneOffsetUser;
                return string.Format(DateTimeFormat.YESTERDAY_AT, _dt);
            }
            if (_dayDiff < 7)
            {
                return string.Format(DateTimeFormat.DAYS_AGO, _dayDiff);
            }
            return _dayDiff < 31 ? string.Format(DateTimeFormat.WEEKS_AGO, Math.Ceiling((double)_dayDiff / 7)) : DateFormat(_date);

            // Default full date format
        }



        #endregion

        public static String Padding(int _level)
        {

            if (_level <= 1) return "";

            string _out = "|";

            for (int j = 0; j < _level; j++)
            {
                _out += "-";
            }
            return _out;
        }




        public static string ToPlainText(string input, bool convertForUrl)
        {

            return Utils.ToPlainText(input, convertForUrl);
        }

        //public static string ToPlainText(string input)
        //{
        //    return ToPlainText(input, false);
        //}


        #region Paging

        public static int PageIndex
        {
            get
            {
                int _pageSize;
                int.TryParse(Context.Request.QueryString["P"], out _pageSize);
                return _pageSize > 0 ? _pageSize : 1;
            }

        }

        public static int PageSize
        {
            get
            {
                int _pageSize;
                int.TryParse(ConfigurationManager.AppSettings["PageSize"], out _pageSize);

                if (_pageSize <= 0)
                {
                    return 10;
                }
                return _pageSize;




            }
        }


        #region PageRender


        public static string PageRender(string pageFormatString, int totalRows)
        {
            return PageRender(pageFormatString, PageIndex, PageSize, totalRows);
        }

        public static string PageRender(string pageFormatString, int pageIndex, int pageSize, int totalRows)
        {

            var totalPage = (int)Math.Ceiling((double)totalRows / pageSize);

            if (totalPage <= 1) return string.Empty;

            const int pageButtonCount = 3;
            int min = pageIndex - pageButtonCount;
            int max = pageIndex + pageButtonCount;

            if (max > totalPage)
                min -= max - totalPage;
            else if (min < 1)
                max += 1 - min;

            var _sb = new StringBuilder(1000);
            bool needDiv = false;


            _sb.Append("<ul class=\"paging\">");


            _sb.Append("<li class=\"page-x-of-y\"><span>");
            _sb.AppendFormat("Trang {0}/{1}", pageIndex, totalPage);
            _sb.Append("</span></li>");

            //Ren Prev Button
            if (pageIndex > 1)
            {
                _sb.AppendFormat(
               "<li class=\"{1}\" onclick=\"window.location='{0}'\"><a title=\"Go to First Page\" href=\"{0}\">&nbsp;&nbsp;</a></li>", string.Format(pageFormatString, 1), "page-first");


                _sb.AppendFormat("<li class=\"page-prev\" onclick=\"window.location='{0}'\"><a href=\"{0}\" title=\"Go to Previous Page\">&nbsp;&nbsp;</a></li>", string.Format(pageFormatString, pageIndex - 1));


            }



            for (int i = 1; i <= totalPage; i++)
            {
                //if (i <= 2 || i > totalPage - 2 || (min <= i && i <= max))
                if ((min <= i && i <= max))
                {

                    string _className = (i == pageIndex) ? "actived" : "page-item";

                    _sb.AppendFormat("<li onclick=\"window.location='{0}'\" class=\"{1}\"><a href=\"{0}\">{2}</a></li>", string.Format(pageFormatString, i), _className, i);
                    // needDiv = true;
                }
                else if (needDiv)
                {
                    _sb.AppendFormat("<li class=\"{0}\">...</li>", "page-item");
                    needDiv = false;
                }
            }

            //Ren Next Button
            if (pageIndex < totalPage)
            {
                _sb.AppendFormat(
                    "<li class=\"{1}\" onclick=\"window.location='{0}'\"><a title=\"Go to Next Page\" href=\"{0}\">&nbsp;&nbsp;</a></li>", string.Format(pageFormatString, pageIndex + 1), "page-next");

                _sb.AppendFormat(
                  "<li class=\"{1}\" onclick=\"window.location='{0}'\"><a title=\"Go to Last Page\" href=\"{0}\">&nbsp;&nbsp;</a></li>", string.Format(pageFormatString, totalPage), "page-last");


            }


            _sb.Append("</ul>");

            return _sb.ToString();


        }

        #endregion

        //public static string PageRender(string pageFormatString, int pageIndex, int totalRows)
        //{

        //    int totalPage = TotalPage(PageSize, totalRows);

        //    if (totalPage <= 1) return string.Empty;

        //    const int pageButtonCount = 3;
        //    int min = pageIndex - pageButtonCount;
        //    int max = pageIndex + pageButtonCount;

        //    if (max > totalPage)
        //        min -= max - totalPage;
        //    else if (min < 1)
        //        max += 1 - min;

        //    var _sb = new StringBuilder(1000);
        //    bool needDiv = false;

        //    _sb.AppendFormat("<div class=\"{0}\">", "page-container");
        //    _sb.AppendFormat("<table cellpadding=\"0\" cellspacing=\"1\" style=\"width:auto;\"><tr>");

        //    _sb.AppendFormat("<td class=\"{0}\">", "page-x-of-y");

        //    _sb.Append(string.Format("Page {0} of {1}", pageIndex, totalPage));

        //    _sb.Append("</td>");


        //    //Ren Prev Button
        //    if (pageIndex > 1)
        //        _sb.AppendFormat(
        //            "<td onclick=\"{0}\" class=\"{1}\"><a href=\"{0}\">«</a></td>",
        //            string.Format(pageFormatString, pageIndex - 1), "page-item");


        //    for (int i = 1; i <= totalPage; i++)
        //    {
        //        if (i <= 2 || i > totalPage - 2 || (min <= i && i <= max))
        //        {

        //            string _className = (i == pageIndex) ? "page-item-actived" : "page-item";

        //            _sb.AppendFormat("<td onclick=\"{0}\" class=\"{1}\"><a href=\"{0}\">{2}</a></td>", string.Format(pageFormatString, i), _className, i);
        //            needDiv = true;
        //        }
        //        else if (needDiv)
        //        {
        //            _sb.AppendFormat("<td class=\"{0}\">...</td>", "page-item");
        //            needDiv = false;
        //        }
        //    }

        //    //Ren Next Button
        //    if (pageIndex < totalPage)
        //        _sb.AppendFormat(
        //            "<td onclick=\"{0}\" class=\"{1}\"><a href=\"{0}\">&#187;</a></td>",
        //            string.Format(pageFormatString, pageIndex + 1), "page-item");

        //    _sb.Append("</tr></table>");
        //    _sb.Append("</div>");



        //    return _sb.ToString();
        //}



        #endregion


        #region Logging


        private static String LoggingPath
        {
            get
            {
                // return HttpContext.Current.Server.MapPath();

                string _path = ConfigurationManager.AppSettings["LoggingPath"];

                if (!Directory.Exists(Context.Server.MapPath(_path)))
                {

                    Directory.CreateDirectory(Context.Server.MapPath(_path));
                }

                return Context.Server.MapPath(_path);
            }
        }


        public static String ClassToString(object _o)
        {
            Type t = _o.GetType();
            PropertyInfo[] pi = t.GetProperties();
            var _sb = new StringBuilder();
            foreach (PropertyInfo prop in pi)
            {
                _sb.Append(_sb.Length > 0 ? " | " : string.Empty);

                _sb.Append(prop.Name + ":" + prop.GetValue(_o, null));

            }

            return _sb.ToString();


        }


        public static void Log(String logMsg)
        {

            string _fileLog = DateTime.Now.ToString("yyyyMMdd") + ".txt";

            using (StreamWriter w = File.AppendText(LoggingPath + _fileLog))
            {
                Log(logMsg, w);
                // Close the writer and underlying file.
                w.Close();
            }

        }


        public static void Log(String logMessage, TextWriter w)
        {

            w.WriteLine("[{0}] : {1}", DateTime.Now.ToString("yyyyMMdd HH:mm:ss tt"), logMessage);
            w.WriteLine("-------------------------------");
            w.Flush();
        }


        #endregion


        public static string CheckImage(object image)
        {
            if (image != null && image.ToString().Length > 3)
                return string.Format("{0}{1}", WebConfig.ImagePrefix, image);
            return ConfigurationManager.AppSettings["NoImage"];

        }


        public static string ImageRender(string image, int width, int height)
        {
            if (image != null && image.Length > 3)
                return string.Format("{0}{1}&w={2}&h={3}", WebConfig.ImagePrefix, image, width, height);
            return ConfigurationManager.AppSettings["NoImage"];

        }

        public static string ImageRender(string image)
        {
            if (image != null && image.Length > 3)
                return string.Format("{0}{1}", WebConfig.ImagePrefix, image);
            return null;

        }

        public static string ImageRender(string image, int size)
        {
            if (image != null && image.Length > 3)
                return string.Format("{0}{1}&w={2}", WebConfig.ImagePrefix, image, size);
            return ConfigurationManager.AppSettings["NoImage"];

        }


        /// <summary>
        /// Wraps matched strings in HTML span elements styled with a background-color
        /// </summary>
        /// <param name="text"></param>
        /// <param name="keywords">Comma-separated list of strings to be highlighted</param>
        /// <param name="cssClass">The Css color to apply</param>
        /// <param name="fullMatch">false for returning all matches, true for whole word matches only</param>
        /// <returns>string</returns>
        public static string HighlightKeyWords(this string text, string keywords, bool fullMatch)
        {
            if (text == String.Empty || keywords == String.Empty)
                return text;
            var words = keywords.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (!fullMatch)
                return words.Select(word => word.Trim()).Aggregate(text,
                             (current, pattern) =>
                             Regex.Replace(current,
                                             pattern,
                                               string.Format("<span class=\"highlight\">{0}</span>",
                                               "$0"),
                                               RegexOptions.IgnoreCase));
            return words.Select(word => "\\b" + word.Trim() + "\\b")
                        .Aggregate(text, (current, pattern) =>
                                  Regex.Replace(current,
                                  pattern,
                                    string.Format("<span class=\"highlight\">{0}</span>",
                                    "$0"),
                                    RegexOptions.IgnoreCase));

        }



        public static string HighlightKeywords(this string input, string keywords)
        {
            if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(keywords))
            {
                return input;
            }

            string[] _kws = keywords.Split(' ');
            foreach (string _k in _kws)
            {
                try
                {
                    input = Regex.Replace(input, _k, string.Format("<span class=\"highlight\">{0}</span>", "$0"), RegexOptions.IgnoreCase);
                }
                catch
                {
                    //
                }
            }
            return input;
        }


        public static string HighlightKeywords(this string input)
        {

            string _hl = Context.Request.QueryString["highlight"];

            return input.HighlightKeywords(_hl);



        }


        /// <summary>
        /// Finds web and email addresses in a string and surrounds then with the appropriate HTML anchor tags 
        /// </summary>
        /// <param name="s"></param>
        /// <returns>String</returns>
        public static string AutoParseLink(this string s)
        {
            //Finds URLs with no protocol
            var _urlregex = new Regex(@"\b\({0,1}(?<url>(www|ftp)\.[^ ,""\s<)]*)\b",
              RegexOptions.IgnoreCase | RegexOptions.Compiled);
            //Finds URLs with a protocol
            var _httpurlregex = new Regex(@"\b\({0,1}(?<url>[^>](http://www\.|http://|https://|ftp://)[^,""\s<)]*)\b",
              RegexOptions.IgnoreCase | RegexOptions.Compiled);
            //Finds email addresses
            var _emailregex = new Regex(@"\b(?<mail>[a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)\b",
              RegexOptions.IgnoreCase | RegexOptions.Compiled);
            s = _urlregex.Replace(s, " <a href=\"http://${url}\" rel=\"_blank\">${url}</a>");
            s = _httpurlregex.Replace(s, " <a href=\"${url}\" rel=\"_blank\">${url}</a>");
            s = _emailregex.Replace(s, "<a href=\"mailto:${mail}\">${mail}</a>");
            return s;
        }



        public static string BbCodeToHtml(this string html)
        {
            const RegexOptions _options = RegexOptions.Singleline | RegexOptions.IgnoreCase;


            var _regex = new Regex(@"\[quote=(.*?)\](.*)\[/quote\]", _options);

            while (_regex.IsMatch(html))
                html = _regex.Replace(html, "<div class=\"quote\"><div class=\"quote-head\">$1:</div><div class=\"quote-content\">$2</div></div>");

            // html = Regex.Replace(html, @"\[quote=(.*?)\](.*)\[/quote\]", "<div class=\"quote\"><div class=\"quote-poster\">$1:</div><div class=\"quote-content\">$2</div></div>", _options);

            _regex = new Regex(@"\[quote\](.*)\[/quote\]", _options);

            while (_regex.IsMatch(html))
            {
                html = _regex.Replace(html, "<div class=\"quote\"><div class=\"quote-content\">$1</div></div>");
            }


            // html = Regex.Replace(html, @"\[quote\](.*)\[/quote\]", "<div class=\"quote\"><div class=\"quote-content\">$1</div></div>", _options);



            _regex = new Regex(@"\[code=(.*?)\](.*?)\[/code\]", _options);

            if (_regex.IsMatch(html))
                html = _regex.Replace(html, "<code name=\"code\" class=\"brush: {1}\">$2</code>");

            //  _regex = new Regex(@"\[hide](.*)\[/hide\]", _options);

            //if (_regex.IsMatch(html) && !Logined)
            //    html = _regex.Replace(html, Configuration.);

            // YouTube

            //_regex = new Regex(@"http:\/\/(?:www\.)?youtube.com\/watch\?(?=.*v=[a-zA-Z0-9_\-]+)(?:\S+)?$");//new Regex(@"\[youtube\]http:\/\/([a-zA-Z]+.)youtube.com\/watch\?v=([a-zA-Z0-9_\-]+)\[\/youtube\]", _options);


            _regex = new Regex(@"\[youtube\](.*?)\[\/youtube\]", _options);


            if (_regex.IsMatch(html))
            {
                html.Replace(html,
                            @"<object width=""425"" height=""344""><param name=""movie"" value=""http://www.youtube.com/v/$1""></param><param name=""allowFullScreen"" value=""true""></param><embed src=""http://www.youtube.com/v/$1"" type=""application/x-shockwave-flash"" allowfullscreen=""true"" width=""425"" height=""344""></embed></object>");

                //html.Replace(html,
                //             @"<object width=""425"" height=""344""><param name=""movie"" value=""http://www.youtube.com/v/$2""></param><param name=""allowFullScreen"" value=""true""></param><embed src=""http://www.youtube.com/v/$2"" type=""application/x-shockwave-flash"" allowfullscreen=""true"" width=""425"" height=""344""></embed></object>");
            }


            return html;

        }



        public static void MapBoolean(string expected, out bool value)
        {
            value = !string.IsNullOrEmpty(expected) && Regex.IsMatch(expected, "yes|y|on|true", RegexOptions.IgnoreCase);
        }

        public static string TruncateAtWord(this string input, int length)
        {
            if (input == null || input.Length < length)
                return input;
            input = input.Replace("&nbsp;", " ");
            int _iNextSpace = input.LastIndexOf(" ", length);
            return string.Format("{0}...", input.Substring(0, (_iNextSpace > 0) ? _iNextSpace : length).Trim());
        }

        public static string ToPlainText(this string input)
        {
            return Utils.ToPlainText(input, true);
        }

        //public static string NewsLinkDetail(string category, int id, string subject)
        //{


        //    return string.Format("{4}/{0}/{1}.D{2}{3}", category.ToPlainText(), subject.ToPlainText(), id.ToString("X"), Extension, Domain);
        //}


        ////public static string NewsLinkDetail(DateTime dateTime, int id, string subject)
        ////{
        ////    return string.Format("/{0}/{1}/{2}/{3}{4}", dateTime.Year, dateTime.Month, id,
        ////                         Utils.ToPlainText(subject, true), Extension);
        ////}


        //public static string CategoryLink(int id, string parentName, string name)
        //{
        //    return string.Format("{4}/{0}/{1}.L{2}{3}", parentName, name, id, Extension, Domain);
        //}


        //public static string CategoryLink(int id, string subject)
        //{
        //    return string.Format("{3}/{0}.L{1}{2}", subject.ToPlainText(), id, Extension, Domain);
        //}

        //public static string RssLink(int id, string subject)
        //{
        //    return string.Format("{3}/rss/{0}/{1}{2}", id, subject.ToPlainText(), Extension, Domain);
        //}






        #region UserInfo



        public static UserInfo UserInfo
        {
            get
            {

                //HttpContext.User.Identity.IsAuthenticated
                if (Context.User.Identity.IsAuthenticated)
                {
                    try
                    {

                        HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
                        if (authCookie != null)
                        {
                            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                            var id = new FormsIdentity(authTicket);
                            var principal = new GenericPrincipal(id, null);
                            Context.User = principal;

                            if (HttpContext.Current.Session["_USERINFO"] == null)
                            {
                                string[] _userData = authTicket.UserData.Split(';');

                                var _u = UsersRepo.LogIn(_userData[0], _userData[1], false);
                                HttpContext.Current.Session["_USERINFO"] = _u;
                                return _u;
                            }

                            return (UserInfo)HttpContext.Current.Session["_USERINFO"];
                        }


                        /*
                        var _cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);

                        string[] _userData = FormsAuthentication.Decrypt(_cookie.Value).UserData.Split(';');

                        if (HttpContext.Current.Session["_USERINFO"] == null)
                        {
                            //var _u = UsersRepository.LogIn(_userData[0], _userData[1]);
                            //HttpContext.Current.Session["_USERINFO"] = _u;
                        }

                        return (UserInfo)HttpContext.Current.Session["_USERINFO"];
                         * 
                         * */

                    }
                    catch (Exception ex)
                    {

                        return null;
                    }



                }
                return null;
            }
        }

        //public static bool AllowAccess(Product p)
        //{
        //    return IsLogined && (AllowAccess(p.CatId) || p.UserId == UserInfo.UserId);
        //}


        //public static bool AllowAccess(int groupId)
        //{

        //    return IsLogined && (UserInfo.IsAdmin || UserInfo.IsModerated(groupId));

        //}


        public static bool Logined
        {
            get
            {
                return UserInfo != null;
            }
        }



        #endregion

        #region SetAuthenticationCookie

        public static void SetAuthenticationCookie(string username, string password, bool isPersit)
        {

            var Authticket = new
                           FormsAuthenticationTicket(1,
                           username,
                           DateTime.Now,
                           DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                           true,
                           string.Format("{0};{1}", username, password),
                           FormsAuthentication.FormsCookiePath);

            string hash = FormsAuthentication.Encrypt(Authticket);

            var Authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash)
            {
                HttpOnly = FormsAuthentication.RequireSSL,
                Path = FormsAuthentication.FormsCookiePath,
                Domain = FormsAuthentication.CookieDomain
            };

            if (Authticket.IsPersistent) Authcookie.Expires = Authticket.Expiration;

            Context.Response.AppendCookie(Authcookie);

        }

        public static void SignOut()
        {
            FormsAuthentication.SignOut();

            HttpCookie cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie != null)
            {
                cookie.Expires = DateTime.UtcNow.AddYears(-999);
                Context.Response.Cookies.Add(cookie);
            }

            //Context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            Context.Session.Clear();
            Context.Session.Abandon();

            //Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            //Context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
            //Context.Response.Cache.SetNoStore();
            //Context.Response.AppendHeader("Pragma", "no-cache");



        }

        #endregion

        public static string RemoveIllegalCharacters(object input)
        {

            if (input == null) return "";
            // cast the input to a string
            string data = input.ToString();

            // replace illegal characters in XML documents with their entity references
            data = data.Replace("&", "&amp;");
            data = data.Replace("\"", "&quot;");
            data = data.Replace("'", "&apos;");
            data = data.Replace("<", "&lt;");
            data = data.Replace(">", "&gt;");

            return data;
        }



        #region DateTime Format


        public static TimeSpan TimeZone
        {
            get
            {
                //float min = ForumConfiguration.Instance.TimeZoneOffset * 60;
                return TimeSpan.FromHours(WebConfig.TimeZone);
                // return new TimeSpan(min / 60, min % 60, 0);
            }
        }

        /// <summary>
        /// Returns the user timezone offset from GMT
        /// </summary>
        public static TimeSpan TimeZoneOffsetUser
        {
            get
            {
                //if (UserInfo != null)
                //{


                //    return TimeSpan.FromHours(UserInfo.TimeZone);
                //    //return new TimeSpan(min / 60, min % 60, 0);


                //}
                return TimeZone;
            }
        }


        public static string DateFormat(DateTime _dateTime)
        {
            DateTime _dt = _dateTime + TimeZoneOffsetUser;

            return _dt.ToString(DateTimeFormat.DATE_FORMAT);
        }

        public static string ShortDateTimeFormat(DateTime _dateTime)
        {
            DateTime _dt = _dateTime + TimeZoneOffsetUser;

            return _dt.ToString(WebConfig.DateTimeFormat);
        }

        public static string TimeFormat(DateTime _datetime)
        {

            _datetime += TimeZoneOffsetUser;
            try
            {
                return _datetime.ToString("hh:mm tt");
            }
            catch (Exception)
            {
                return _datetime.ToString("T");
            }
        }


        //public static string PrettyDate(DateTime _date)
        //{
        //    // 1.
        //    // Get time span elapsed since the date.
        //    TimeSpan _s = DateTime.UtcNow.Subtract(_date);

        //    // 2.
        //    // Get total number of days elapsed.
        //    var _dayDiff = (int)_s.TotalDays;

        //    // 3.
        //    // Get total number of seconds elapsed.
        //    var _secDiff = (int)_s.TotalSeconds;

        //    // 4.
        //    // Don't allow out of range values.
        //    if (_dayDiff < 0 || _dayDiff >= 31)
        //    {
        //        return DateTimeFormat(_date);
        //    }

        //    // 5.
        //    // Handle same-day times.
        //    if (_dayDiff == 0)
        //    {
        //        // A.
        //        // Less than one minute ago.
        //        if (_secDiff < 60)
        //        {
        //            return string.Format(GetDate("JUST_NOW"), _secDiff == 0 ? 1 : _secDiff); //"just now";
        //        }
        //        // B.
        //        // Less than 2 minutes ago.
        //        if (_secDiff < 120)
        //        {
        //            return string.Format(GetDate("MINUTES_AGO"), 1);// "1 minute ago";
        //        }
        //        // C.
        //        // Less than one hour ago.
        //        if (_secDiff < 3600)
        //        {
        //            return string.Format(GetDate("MINUTES_AGO"),
        //                Math.Floor((double)_secDiff / 60));
        //        }
        //        // D.
        //        // Less than 2 hours ago.
        //        if (_secDiff < 7200)
        //        {
        //            return string.Format(GetDate("HOURS_AGO"), 1); ;
        //        }
        //        // E.
        //        // Less than one day ago.
        //        if (_secDiff < 86400)
        //        {
        //            return string.Format(GetDate("HOURS_AGO"),
        //                Math.Floor((double)_secDiff / 3600));
        //        }
        //    }
        //    // 6.
        //    // Handle previous days.
        //    if (_dayDiff == 1)
        //    {
        //        var _dt = _date + TimeZoneOffsetUser;
        //        return string.Format(GetDate("YESTERDAY_AT"), _dt);
        //    }
        //    if (_dayDiff < 7)
        //    {
        //        return string.Format(GetDate("DAYS_AGO"), _dayDiff);
        //    }
        //    return _dayDiff < 31 ? string.Format(GetDate("WEEKS_AGO"), Math.Ceiling((double)_dayDiff / 7)) : DateTimeFormat(_date);

        //    // Default full date format
        //}



        #endregion


        #region Validate

        public static bool UserNameIsDisallowed(string name)
        {


            if (!String.IsNullOrEmpty(WebConfig.DisallowedUserNames))
            {
                const string regExWildcard = @"[\w\W]*?"; //"[a-zA-Z0-9]*";
                const RegexOptions regExOpt = RegexOptions.IgnoreCase;
                string[] _Names = WebConfig.DisallowedUserNames.Split(new char[] { ',', ';' });

                return _Names.Select(s => String.Format(@"^{0}$", s.Replace("*", regExWildcard))).Select(thePattern => new Regex(thePattern, regExOpt)).Any(regEx => regEx.IsMatch(name));
            }
            return false;
        }


        public static bool AllowEmail(string email)
        {

            if (string.IsNullOrEmpty(WebConfig.AllowEmails) || "*".Equals(WebConfig.AllowEmails))
            {
                return true;
            }
            else
            {
                const string regExWildcard = @"[_a-z0-9-]+(\.[_a-z0-9-]+)*";//@"[^\w\-\.]";//"[A-Z0-9._%+-]+";
                const RegexOptions regExOpt = RegexOptions.IgnoreCase;
                string[] _Names = WebConfig.AllowEmails.Split(new char[] { ',', ';' });

                return _Names.Select(s => String.Format(@"^{0}$", s.Replace("*", regExWildcard))).Select(thePattern => new Regex(thePattern, regExOpt)).Any(regEx => regEx.IsMatch(email));

            }
        }


        #endregion


        #region Send Mail


        public static void SendMail(string from, string to, string subject, string body)
        {
            //var _sender = new SmtpSender(Configuration.SmtpServer);

            //_sender.Port = Configuration.SmtpPort;
            //_sender.EnableSsl = Configuration.SmtpSsl;

            //_sender.UserName = Configuration.SmtpUserName;
            //_sender.Password = Configuration.SmtpUserPass;

            //_sender.Send(from,to,subject,msg);


            var _mail = new MailMessage(new MailAddress(from, WebConfig.SiteName), new MailAddress(to)) { ReplyTo = new MailAddress(WebConfig.SmtpReplyTo) };

            _mail.Subject = string.Format("[{0}] - {1}", WebConfig.SiteName, subject);
            _mail.Body = body + GetText("Email", "signature");
            _mail.BodyEncoding = Encoding.UTF8;
            //_mail.CC.Add();
            _mail.Bcc.Add(new MailAddress(WebConfig.SiteName));
            _mail.IsBodyHtml = true;
            _mail.Priority = MailPriority.High;
            //SmtpClient smtpMail = new SmtpClient("smtp.gmail.com");
            var _smtpMail = new SmtpClient(WebConfig.SmtpServer);
            _smtpMail.Port = WebConfig.SmtpPort;
            _smtpMail.EnableSsl = WebConfig.SmtpSsl;

            if (!string.IsNullOrEmpty(WebConfig.SmtpUserName) && !string.IsNullOrEmpty(WebConfig.SmtpUserPass))
            {

                _smtpMail.Credentials = new NetworkCredential(WebConfig.SmtpUserName, WebConfig.SmtpUserPass);
            }

            // and then send the mail
            _smtpMail.Send(_mail);


        }


        #endregion




        #region GetText

        public static string GetText(string path, string fileName)
        {

            string textPath = Context.Server.MapPath(WebConfig.ApplicationPath + "Text");

            string filePath = string.IsNullOrEmpty(path)
                                  ? string.Format("{0}\\{1}.txt", textPath, fileName)
                                  : string.Format("{0}\\{1}\\{2}.txt", textPath, path, fileName);

            using (StreamReader re = File.OpenText(filePath))
            {
                return re.ReadToEnd();
            }

        }

        public static string GetText(string fileName)
        {
            return GetText(null, fileName);
        }


        #endregion

    }

}
